import { Table, Popconfirm, Button } from 'antd';
import React, { useState, useEffect } from 'react';
import { produce, Draft } from 'immer';
import { useApi } from 'hooklib/async';

type IProductList = { name: string }[];
type opById = (id: string) => void;

// 数据和数据的操作都封装到一个 hook 中
function useProductList(products: IProductList) {
  const [productList, setProducts] = useState(products);
  const onDelete = (id: string) => {
    const idx = productList.findIndex(v => v.name === id);
    const useImmer = true;
    if (!useImmer) {
      productList.splice(idx, 1);
      setProducts([...productList]); // 传统的产生新状态的方式
    } else {
      setProducts(
        produce((draft: Draft<IProductList>) => {
          draft.splice(idx, 1);
        }),
      ); // 使用 immer 直接操作数据的方式设置新状态
    }
  };
  return { productList, onDelete };
}

const ProductList: React.FC<{
  products: IProductList;
}> = ({ products }) => {
  const { productList, onDelete } = useProductList(products);
  const ts = useApi([], () => ['/dir/path']);
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
    },
    {
      title: 'Actions',
      render: (text: any, record: any) => {
        return (
          <Popconfirm title="Delete?" onConfirm={() => onDelete(record.id)}>
            <Button>Delete </Button>
          </Popconfirm>
        );
      },
    },
  ];
  return (
    <div>
      <h4>{ts.o && JSON.stringify(ts.d)}</h4>
      <Table dataSource={productList} columns={columns} rowKey="name" />
    </div>
  );
};

export default ProductList;
